export function windowError(infoObj = {}) {
  return function(errorMessage, scriptURI, lineNo, columnNo, error) {
    if (errorMessage === 'Script error.') {
      error = { message: 'Script error.' }
    }
    let errorObj = {
      errorMessage: errorMessage || null,
      scriptURI: scriptURI || null,
      lineNo: lineNo || null,
      columnNo: columnNo || null,
      stack: error && error.stack ? error.stack : null,
      info: infoObj.window
    }
    console.log(errorObj)
    // consume(errorObj)
  }
}

export function vueHandler(infoObj = {}) {
  return function(err, vm, info) {
    let errinfo = getFileInfo(err.stack)
    let errorMessage = err.message
    let errorObj = {
      errorMessage: errorMessage || null,
      scriptURI: errinfo.scriptURI || null,
      lineNo: errinfo.lineNo || null,
      columnNo: errinfo.columnNo || null,
      stack: err && err.stack ? err.stack : null,
      info: { ...infoObj.vue, vueinfo: info }
    }
    console.error(errorObj)
  }
}

function getFileInfo(stack) {
  let start = stack.indexOf('at ')
  let newStack = stack.substr(start)
  let lineEnd = newStack.indexOf('\n')
  newStack = newStack.substr(0, lineEnd)
  let strArr = newStack.split('/')
  let fileNameStr = strArr[strArr.length - 1]
  let [scriptURI, lineNo, columnNo] = fileNameStr.split(':')
  columnNo = columnNo.substr(0, columnNo.length - 1)
  return { scriptURI, lineNo, columnNo }
}

function consume(errorObj) {
  // window.navigator.userAgent
  if (XMLHttpRequest) {
    var xhr = new XMLHttpRequest()
    xhr.open('post', '/middleware/errorMsg', true) // 上报给node中间层处理
    xhr.setRequestHeader('Content-Type', 'application/json') // 设置请求头
    xhr.send(JSON.stringify(errorObj)) // 发送参数
  }
}
